﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using COFE.Core.Utils;

namespace COFE.Core.Actions
{
    public abstract class ScheduleBase : ISchedule
    {
        protected ScheduleBase(IUserProfile user, 
            WorkPriority priority, IWork work, int retryCount)
        {
            Id = Guid.NewGuid();            
            Work = work;
            User = user;
            ScheduledTimeUtc = DateTime.MinValue;            
            RetryCount = retryCount;
            Priority = priority;

            string lib, typ, p;
            WorkUtils.ParseWorkName(work.Name, 
                out lib, out typ, out p);
            WorkLib = lib; WorkType = typ; WorkParam = p;
        }

        protected ScheduleBase(WorkPriority priority, IWork work, int retryCount)
            : this(COFEShared.CurrentUserProfile, 
            priority, work, retryCount)
        {

        }

        protected ScheduleBase(WorkPriority priority, IWork work)
            : this(COFEShared.CurrentUserProfile,
            priority, work, COFEActionShared.WorkScheduler.RetryCount)
        {

        }

        public virtual bool CheckCanRetry()
        {
            if (RetryCount > 0)
            {
                RetryCount--;
                return true;
            }
            return false;
        }

        public override string ToString()
        {
            return Id.ToString();
        }

        #region Public Properties

        public Guid Id { get; private set; }
        public string Name { get { return Work.Name; } }
        public string WorkLib { get; private set; }
        public string WorkType { get; private set; }
        public string WorkParam { get; private set; }
        public IWork Work { get; private set; }
        public IUserProfile User { get; private set; }
        public virtual WorkPriority Priority { get; protected set; }
        public virtual bool IsFinished
        {
            get
            {
                return RetryCount == 0 ||
                       ((Work.Result != null) && Work.Result.Success);
            }
        }
        public DateTime ScheduledTimeUtc { get; set; }
        public DateTime StartTimeUtc { get { return Work.StartTimeUtc; } }
        public DateTime EndTimeUtc { get { return Work.EndTimeUtc; } }
        public Exception LastError { get { return Work.Result != null ? Work.Result.Error : null; } }
        public int RetryCount { get; set; }

        public bool IsCancelled { get { return Priority == WorkPriority.Cancelled; } }

        #endregion                                   
    }
}
